<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '发布',
  },
}
</route>
<template>
  <view class="bg-white overflow-hidden w-100% box-border">
    <view class="mb-100rpx">
      <wd-form ref="form" :model="model" :rules="rules">
        <wd-cell title="我的需求" vertical prop="demand">
          <wd-radio-group v-model="model.demand" shape="dot" inline @change="change">
            <wd-radio :value="'我要买'">我要买</wd-radio>
            <wd-radio :value="'我要卖'">我要卖</wd-radio>
          </wd-radio-group>
        </wd-cell>
        <wd-cell title="标签" vertical prop="tag">
          <wd-tag
            v-model="model.tag"
            v-for="(tag, index) in tags"
            :key="index"
            custom-class="space"
            round
            closable
            @close="handleClose(index)"
          >
            {{ tag }}
          </wd-tag>
          <wd-tag
            v-if="tags.length < 3"
            custom-class="space"
            round
            dynamic
            @confirm="handleConfirm"
          ></wd-tag>
        </wd-cell>
        <wd-cell title="量（公斤）" vertical prop="quantity">
          <wd-input
            v-model="model.quantity"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：100"
          />
        </wd-cell>
        <wd-cell title="需求描述" vertical prop="remark">
          <view class="text-#f40d0d text-24rpx h-34rpx lh-20rpx">
            不实信息会给他人带来困扰，务必真实描述！
          </view>
          <wd-button icon="user-talk" plain @touchstart="startRecording" @touchend="stopRecording">
            长按语音输入
          </wd-button>
          <!-- 语音音阶动画 长按说话时的动画 -->
          <view class="prompt" v-if="animation" style="z-index: 2">
            <section class="dots-container">
              <view class="dot" v-for="(_, index) in 5" :key="index"></view>
            </section>
            <text>录音中...</text>
          </view>
          <wd-textarea
            v-model="model.remark"
            :maxlength="300"
            :show-word-limit="true"
            @change="handleArea"
            placeholder="请输入你想购买/出售的需求，例如产品名称、购买/出售量、购买/出售时间、联系电话和地址等信息~"
          />
        </wd-cell>
        <wd-cell title="添加图片" vertical prop="files">
          <wd-upload
            ref="uploadImg"
            :file-list="model.files"
            :limit="6"
            multiple
            name="file"
            image-mode="aspectFill"
            :action="actions"
            @change="handleFileChange"
            @success="handleChange"
            @remove="handleRemove"
            class="bg-#fff"
          ></wd-upload>
        </wd-cell>
      </wd-form>
    </view>
    <view class="footer_cont">
      <view class="footer m-20rpx" @click="submitHandler">提交</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useToast } from 'wot-design-uni'
import * as getApi from '@/service/FruitMarket/index'

import { useUserStore } from '@/store'
import _ from 'lodash'
const reportType = ref(1)
const userStore = useUserStore()
const toast = useToast()
const baseurl = ref(import.meta.env.VITE_SERVER_BASEURL)
const actions: string = baseurl.value + '/app-api/infra/file/business/upload'
const form = ref()
const showButton = ref(false)
const showType = ref()
const uploadImg = ref(null)
const saveId = ref()
const userId = computed(() => userStore.userInfo.userId)
const model = reactive<{
  tag: string
  demand: string
  quantity: string
  remark: string
  files: any[]
}>({
  tag: '',
  demand: '我要买',
  remark: '',
  quantity: '',
  files: [],
})
function change(value) {
  // console.log(value)
}
const compress = true
// form表单验证
const rules: FormRules = {
  quantity: [
    {
      required: true,
      message: '购买/出售量不能为空，请输入需求量！',
      trigger: 'change',
      validator: (value, rule) => {
        value = value.trim()
        if (!value) {
          return Promise.reject(new Error('购买/出售量不能为空，请输入需求量！'))
        }
        const numValue = parseFloat(value)
        if (isNaN(numValue)) {
          return Promise.reject(new Error('需求量必须是有效的数字!'))
        }
        return Promise.resolve(true)
      },
    },
  ],
  demand: [
    {
      required: true,
      message: '请选择我的需求',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请选择我的需求'))
        }
      },
    },
  ],
  remark: [
    {
      required: true,
      message: '需求描述不能为空，请输入需求描述！',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入需求描述'))
        }
      },
    },
  ],
}
defineOptions({
  name: 'addProducts',
})
// 图片
function handleChange({ file }) {
  const { response } = file
  const code = JSON.parse(response).code
  if (code != -1) {
    const fileId = JSON.parse(response).data.id
    file.fileId = fileId
    model.files.push(file)
  } else {
    model.files = [...model.files]
    toast.error({ msg: '图片违规', duration: 2000 })
  }
}
function handleFileChange({ fileList }) {
  // console.log(fileList, 'fileList')
  //   model.fileList = fileList
}
function handleRemove({ file }) {
  model.files = model.files.filter((item) => {
    return item.uid !== file.uid
  })
}
// 标签
const tags = ref([])
function handleClose(order) {
  tags.value = tags.value.filter((value, index) => index !== order)
}
function handleConfirm({ value }) {
  if (!value) return
  tags.value = [...tags.value, value]
  if (tags.value.length === 3) {
    toast.error({ msg: '标签最多三个，可删除不用标签添加新的！', duration: 2000 })
  }
}
// 语音输入
const currentText = ref('')
const animation = ref(false)
const plugin = requirePlugin('WechatSI')
const manager = plugin.getRecordRecognitionManager()
manager.onStop = (res) => {
  currentText.value = res.result
  model.remark = model.remark + currentText.value
  animation.value = false
}

const startRecording = () => {
  animation.value = true
  manager.start({ lang: 'zh_CN' })
  manager.onRecognize = (res) => {
    model.remark = model.remark + res.result
  }
}
const stopRecording = () => {
  animation.value = false
  // console.log('结束')
  manager.stop()
}
const handleArea = () => {
  model.remark = model.remark + currentText.value
}
const idList = ref([])
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
// 表单提交
const handleSubmit = async () => {
  if (Array.isArray(tags.value)) {
    model.tag = tags.value.join(',')
  }
  const fileIds = ref([])
  model.files.forEach((item) => {
    if (item.fileId) {
      fileIds.value.push(item.fileId)
    }
    if (item.id) {
      fileIds.value.push(item.id)
    }
  })
  const newFilesSet = [...new Set(fileIds.value)]
  idList.value = newFilesSet
  try {
    const { valid, errors } = await form.value.validate()
    if (!valid) {
      return
    }
    const creatorVo = {
      userId: userId.value,
    }
    const apiCall = showType.value === 'add' ? getApi.ceratefreshFruit : getApi.updatefreshFruit
    // 调用API
    try {
      const { code } = await apiCall({
        ...model,
        ...creatorVo,
        id: saveId.value,
        files: idList.value,
      })
      console.log(code)
      if (code == 0) {
        toast.success({ msg: '提交成功', duration: 2000 })
        setTimeout(() => {
          uni.navigateBack({ delta: 1 })
          toast.close()
        }, 1000)
      } else {
        toast.error({ msg: '内容违规', duration: 2000 })
      }
    } catch (error) {
      toast.error({ msg: '提交失败', duration: 2000 })
    }
  } catch (validationError) {
    toast.error({ msg: '表单验证异常', duration: 2000 })
  }
}

onLoad((options) => {
  // console.log('tab:', options.tab)
  showType.value = options.type
  if (options.type === 'edit') {
    const item = JSON.parse(decodeURIComponent(options.data || '{}'))
    saveId.value = item.id
    tags.value = item.tag
    model.demand = item.demand
    model.remark = item.remark
    model.quantity = item.quantity
    model.files = item.fileDOList
    // model.files = item.fileDOList.map((val) => {
    //   return { ...val, url: baseurl.value + val.url }
    // })
  }
})
</script>

<style lang="scss" scoped>
::v-deep .wd-textarea {
  padding: 0 !important;
}
::v-deep .wd-textarea::after,
::v-deep .wd-input::after {
  height: 0 !important;
}
::v-deep .wd-textarea__value,
::v-deep .wd-input__value {
  padding: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-textarea__value {
  padding-bottom: 100rpx !important;
}
::v-deep textarea {
  height: 200px !important;
}
::v-deep .wd-textarea__count,
::v-deep .wd-input__count {
  right: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-cell__title {
  font-size: 28rpx !important;
  font-weight: bold !important;
  color: #333 !important;
}
::v-deep .wd-cell__right {
  margin-top: 20rpx !important;
}
::v-deep .wd-tag.is-default.is-round {
  line-height: 32rpx !important;
  color: #f72323 !important;
  border-color: #ee2a02 !important;
  border-radius: var(--wot-tag-round-radius, 8rpx) !important;
}
:deep(.space) {
  margin: 10rpx 10rpx 0 0;
}
::v-deep .wd-tag__close {
  line-height: 32rpx !important;
  vertical-align: baseline !important;
}
::v-deep .wd-tag__add {
  vertical-align: baseline !important;
}
::v-deep .wd-tag__text {
  vertical-align: baseline !important;
}
::v-deep .wd-upload__mask {
  background: transparent !important;
}
::v-deep .wd-radio-group {
  line-height: 0rpx;
}
::v-deep .wd-radio.is-dot.is-checked .wd-radio__shape {
  background-color: #e66a13 !important;
  border-color: #e66a13 !important;
}
::v-deep .wd-cell__wrapper {
  padding-top: 20rpx !important;
  padding-bottom: 0rpx !important;
}
.footer_cont {
  position: fixed;
  bottom: 0;
  z-index: 3;
  width: 100%;
  background: #fff;
  box-shadow: 0px -3px 6px 0px rgba(201, 201, 201, 0.4);
}
.footer {
  height: 70rpx;
  font-size: 32rpx;
  line-height: 70rpx;
  color: #fff;
  text-align: center;
  background-color: #029669;
  border-radius: 18rpx;
}
.footer:hover {
  opacity: 0.8;
}
::v-deep .wd-button.is-plain.is-primary {
  position: absolute;
  bottom: 20rpx;
  left: 20rpx;
  z-index: 2;
  width: 230rpx;
  height: 60rpx;
  font-size: 24rpx;
  line-height: 60rpx;
  color: rgba(35, 171, 20, 1);
  background-color: #e1f4d7;
  border: 1px solid #029669;
  border-radius: 74rpx;
}
/* 动画 */
.prompt {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 160rpx;
  transform: translate(-50%, -50%);
}

.prompt text {
  position: absolute;
  bottom: 2px;
  left: calc(45%);
  color: white;
  animation: puls 1.5s infinite ease-in-out;
}

.dots-container {
  position: absolute;
  bottom: 0px;
  left: calc(27.5%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 45%;
  height: 80px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 40rpx;
}

.dot {
  width: 28rpx;
  height: 28rpx;
  margin-right: 20rpx;
  background-image: linear-gradient(#5396ff, #aedaff);
  border-radius: 20rpx;
  animation: pulse 1.5s infinite ease-in-out;
}

.dot:last-child {
  margin-right: 0;
}

.dot:nth-child(1) {
  animation-delay: -0.3s;
}

.dot:nth-child(2) {
  animation-delay: -0.1s;
}

.dot:nth-child(3) {
  animation-delay: 0.1s;
}

@keyframes pulse {
  0% {
    background-color: #66a3ff;
    box-shadow: 0 0 0 0 rgba(102, 163, 255, 0.7);
    transform: scale(0.8);
  }

  50% {
    background-color: #add8ff;
    box-shadow: 0 0 0 10px rgba(174, 218, 255, 0);
    transform: scale(1.2);
  }

  100% {
    background-color: #66a3ff;
    box-shadow: 0 0 0 0 rgba(102, 163, 255, 0.7);
    transform: scale(0.8);
  }
}

@keyframes puls {
  0% {
    transform: translateY(0px);
  }

  50% {
    transform: translateY(-4px);
  }

  100% {
    transform: translateY(0px);
  }
}
</style>
